package com.afterglow.lcsrpc.springboot.starter.bootstarp;

import com.afterglow.lcsrpc.RpcApplication;
import com.afterglow.lcsrpc.config.RegistryConfig;
import com.afterglow.lcsrpc.config.RpcConfig;
import com.afterglow.lcsrpc.model.ServiceMetaInfo;
import com.afterglow.lcsrpc.registry.LocalRegistry;
import com.afterglow.lcsrpc.registry.Registry;
import com.afterglow.lcsrpc.registry.RegistryFactory;
import com.afterglow.lcsrpc.springboot.starter.anno.RpcService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

/**
 * Description:Rpc 服务提供者启动
 * Date: 2025/01/12
 * author: lcs
 */
@Slf4j
public class RpcProviderBootStrap implements BeanPostProcessor {
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Class<?> beanClass = bean.getClass();
        RpcService rpcService = beanClass.getAnnotation(RpcService.class);
        if (null != rpcService){
            //需要注册服务
            //1.获取服务基本信息
            Class<?> interfaceClass = rpcService.interfaceClass();
            //默认值处理
            if (interfaceClass == void.class){
                interfaceClass = beanClass.getInterfaces()[0];
            }
            String serviceName = interfaceClass.getName();
            String serviceVersion = rpcService.serviceVersion();
            //2.注册服务
            //本地注册
            LocalRegistry.register(serviceName, beanClass);

            //全局配置
            final RpcConfig rpcConfig = RpcApplication.getRpcConfig();
            //注册服务到注册中心
            RegistryConfig registryConfig = rpcConfig.getRegistryConfig();
            Registry registry = RegistryFactory.getInstance(registryConfig.getRegistry());
            ServiceMetaInfo serviceMetaInfo = new ServiceMetaInfo();
            serviceMetaInfo.setServiceName(serviceName);
            serviceMetaInfo.setServiceVersion(serviceVersion);
            serviceMetaInfo.setServiceHost(rpcConfig.getServerHost());
            serviceMetaInfo.setServicePort(rpcConfig.getServerPort());
            try {
                registry.register(serviceMetaInfo);
            } catch (Exception e) {
                throw new RuntimeException(serviceName + " 服务注册失败", e);
            }

        }
        return bean;
    }
}
